import type { AxiosResponse } from "axios";
import type { CustomError, CustomRequestConfig } from "./types";

/**
 * 日志系统
 * 用于记录请求、响应和错误信息
 */
export class Logger {
  private enabled: boolean;
  private level: "debug" | "info" | "warn" | "error";

  /**
   * 构造函数
   * @param options 日志选项
   */
  constructor(
    options: {
      enabled?: boolean;
      level?: "debug" | "info" | "warn" | "error";
    } = {}
  ) {
    this.enabled = options.enabled ?? import.meta.env.MODE !== "production";
    this.level = options.level ?? "info";
  }

  /**
   * 记录请求日志
   * @param config 请求配置
   */
  public logRequest(config: CustomRequestConfig): void {
    if (!this.enabled) return;

    if (this.level === "debug") {
      const { url, method, params, data, headers } = config;
      console.log(`🚀 REQUEST: ${method?.toUpperCase()} ${url}`, {
        url,
        method: method?.toUpperCase(),
        params,
        data,
        headers: this.sanitizeHeaders(headers)
      });
    }
  }

  /**
   * 记录响应日志
   * @param response 响应对象
   */
  public logResponse(response: AxiosResponse): void {
    if (!this.enabled) return;

    if (this.level === "debug" || this.level === "info") {
      const { config, data, status, statusText } = response;
      console.log(
        `✅ RESPONSE: ${config.method?.toUpperCase()} ${config.url}`,
        {
          status,
          statusText,
          data: this.sanitizeResponseData(data)
        }
      );
    }
  }

  /**
   * 记录错误日志
   * @param error 错误对象
   */
  public logError(error: CustomError): void {
    if (!this.enabled) return;

    const errorInfo = {
      message: error.message,
      code: error.code,
      url: error.config?.url,
      method: error.config?.method?.toUpperCase(),
      isCancel: error.isCancel,
      isTimeout: error.isTimeout,
      isNetworkError: error.isNetworkError
    };

    console.error(
      `❌ ERROR: ${error.config?.method?.toUpperCase()} ${error.config?.url}`,
      errorInfo
    );
  }

  /**
   * 清理响应数据（移除敏感信息或过大的数据）
   * @param data 响应数据
   * @returns 清理后的数据
   */
  private sanitizeResponseData(data: any): any {
    if (!data) return data;

    // 如果是标准的业务响应格式
    if (typeof data === "object" && data.code !== undefined) {
      return {
        code: data.code,
        message: data.message,
        success: data.code === 200 || data.code === 0,
        // 如果data中的data属性特别大，可以考虑简化它
        data: this.simplifyData(data.data)
      };
    }

    return this.simplifyData(data);
  }

  /**
   * 简化数据对象（处理大对象，避免日志过大）
   * @param data 数据对象
   * @returns 简化后的数据
   */
  private simplifyData(data: any): any {
    if (!data) return data;

    if (Array.isArray(data)) {
      if (data.length > 10) {
        return `Array(${data.length}): [${data
          .slice(0, 3)
          .map(item => JSON.stringify(item))
          .join(", ")}, ...]`;
      }
      return data;
    }

    if (typeof data === "object") {
      const keys = Object.keys(data);
      if (keys.length > 10) {
        const preview = {};
        keys.slice(0, 5).forEach(key => {
          preview[key] = data[key];
        });
        return { ...preview, _more: `(${keys.length - 5} more properties)` };
      }
    }

    return data;
  }

  /**
   * 清理请求头（移除敏感信息）
   * @param headers 请求头
   * @returns 清理后的请求头
   */
  private sanitizeHeaders(headers: any): any {
    if (!headers) return headers;

    const sanitizedHeaders = { ...headers };

    // 隐藏敏感的认证信息
    if (sanitizedHeaders.Authorization) {
      sanitizedHeaders.Authorization = "Bearer [HIDDEN]";
    }

    return sanitizedHeaders;
  }

  /**
   * 设置日志级别
   * @param level 日志级别
   */
  public setLevel(level: "debug" | "info" | "warn" | "error"): void {
    this.level = level;
  }

  /**
   * 启用日志
   */
  public enable(): void {
    this.enabled = true;
  }

  /**
   * 禁用日志
   */
  public disable(): void {
    this.enabled = false;
  }
}
